<?php
/**
* @Name : 
* @Function : 
* @Author : Haiwera
* @Created : 2016-11-07
* @Copyright : Haiwera.Fiidee.Monda.Cn
*/
namespace utils\action;

use herosphp\core\Log;
use herosphp\http\HttpRequest;
use herosphp\utils\AjaxResult;
use herosphp\bean\Beans;
use herosphp\core\WebApplication;
use herosphp\files\FileUtils;
use herosphp\files\FileUpload;
use common\action\CommonAction;

class UploadAction extends CommonAction
{
	private $__settingService;

	private $__file_save_path; 
	private $__max_file_size;
	private $__allow_file_ext;

	private $__image_save_path;
	private $__max_image_size;
	private $__allow_image_ext;

	private $__media_save_path;
	private $__max_media_size;
	private $__allow_media_ext;

	public function C_start()
	{
		parent::C_start();
		$this->__settingService = Beans::get('admin.adminSetting.service');

		$this->__file_save_path  = $this->__settingService->getSetting('file_save_path');
		$this->__max_file_size   = $this->__settingService->getSetting('max_file_size');
		$this->__allow_file_ext  = $this->__settingService->getSetting('allow_file_ext');

		$this->__image_save_path = $this->__settingService->getSetting('image_save_path');
		$this->__max_image_size  = $this->__settingService->getSetting('max_image_size');
		$this->__allow_image_ext  = $this->__settingService->getSetting('allow_image_ext');

		$this->__media_save_path = $this->__settingService->getSetting('media_save_path');
		$this->__max_media_size  = $this->__settingService->getSetting('max_media_size');
		$this->__allow_media_ext = $this->__settingService->getSetting('allow_media_ext');
	

	}
	
	public function image_show(HttpRequest $request)
	{
		
		$img_url = trim($_GET["img_url"]);
		$img_path = trim($_GET["img_path"]);
		if ( $img_path != "" && $img_url != "" )  {

			$image = file_get_contents($img_url);
			if ( $image ) {
				@file_put_contents($img_path, $image);
				$this->show_image(imagecreatefromstring($image), $img_url);
			} else {
				die("图片加载失败！");
			}
		}
	}

	public function image_list(HttpRequest $request)
	{
		header("Content-Type:text/html; charset=UTF-8");
		$page = intval($_GET["page"]);
		$offset = ($page - 1) * 15;
		$dir = "/res/upload/mpe/".appId()."/".trim($this->__image_save_path,'/') .'/';
		$image_dir = APP_ROOT . $dir;
		$files = array();
		$handler = opendir($image_dir);
		if ( $handler != false ) {
			$i = 0;
			while ( $filename = readdir($handler) ) {
				if ( $filename != "." && $filename != ".." ) {
					if ( $i <= $offset ) {
						$i++;
						continue;
					}
					$size = getimagesize($dir . $filename);
					array_push($files, array("thumbURL" => $dir . $filename, "oriURL" => $dir .$filename,
					"width" => intval($size[0]), "height" => intval($size[1])));
					$i++;
					if ( $i > $offset + 15 ) break;
				}
			}
			closedir($handler);
		}
		$code = empty($files) ? 1 : 0;
		echo json_encode(array("code" => $code, "data" => $files));
		die();
	}

	public function image_search(HttpRequest $request)
	{
		
		header("Content-Type:text/html; charset=UTF-8");
		set_time_limit(0);
		$page = intval($_GET["page"]);
		$kw = trim($_GET['kw']);
		$apiUrl = "http://image.baidu.com/search/avatarjson?tn=resultjsonavatarnew&ie=utf-8&word={$kw}&pn={$page}&rn=15";
		$content = file_get_contents($apiUrl);
		$data = json_decode(mb_convert_encoding($content, 'UTF-8','GBK,UTF-8'), true);
		$relativeDir = "/res/upload/mpe/".appId() . '/'.trim($this->__image_save_path,'/') .'/';
		$image_dir = APP_ROOT.$relativeDir;

		$files = array();
		if ( is_array($data["imgs"]) ) {
			foreach ( $data["imgs"] as $value ) {
				$filename = basename($value["objURL"]);
				array_push($files, array("thumbURL" => url('/admin/upload/image_show')."?img_url={$value["objURL"]}&img_path=".$relativeDir.$filename,
				"oriURL" => url('/admin/upload/image_show')."?img_url={$value["objURL"]}&img_path=".$relativeDir . $filename,
				"width" => $value["width"], "height" => $value["height"]));
			}
		}

		$code = empty($files) ? 1 : 0;
		echo json_encode(array("code" => $code, "data" => $files));
		die();
	}

	public function upload( HttpRequest $request ) {

		if(count($_FILES) != 1){
		
			AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, L('PARAM_ERROR'));
		}
		$ext = '';
		foreach($_FILES  as $v)
		{
			$ext = $this->get_extension($v['name']);	
		}

		$fileInputName=$request->getParameter('fileInputName');

		$allow_file_ext = explode(',',$this->__allow_file_ext);
		$allow_image_ext = explode(',',$this->__allow_image_ext);
		$allow_media_ext = explode(',',$this->__allow_media_ext);
		if(in_array($ext,$allow_image_ext))
		{
			$dirimage = "/res/upload/mpe/".appId().'/'.trim($this->__image_save_path,'/') .'/'.date('Y')."/".date('m') .'/';
			$config = array(
				"upload_dir" => APP_ROOT.$dirimage,
				//允许上传的文件类型
				'allow_ext' => str_replace(',','|',$this->__allow_image_ext),
				//图片的最大宽度, 0没有限制
				'max_width' => 0,
				//图片的最大高度, 0没有限制
				'max_height' => 0,
				//文件的最大尺寸(KB)
				'max_size' =>  $this->__max_image_size * 1024,     /* 文件size的最大 1MB */
			);
			$upload = new FileUpload($config);
			$result = $upload->upload($fileInputName);
			$filepath = $dirimage . $result['file_name'];
            if ( !$result ) {
                $max = $this->__max_image_size / 1024;
                Log::info("上传图片出错,原因:".$upload->getUploadMessage());
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "请上传小于{$max}MB的图片");
            }

		}
		else if(in_array($ext,$allow_media_ext))
		{
			$dirmedia = "/res/upload/mpe/".appId().'/'.trim($this->__media_save_path,'/') .'/'.date('Y')."/".date('m').'/';
			$config = array(
				"upload_dir" => APP_ROOT.$dirmedia,
				//允许上传的文件类型
				'allow_ext' => str_replace(',','|',$this->__allow_media_ext),
				//文件的最大尺寸(MB)
				'max_size' =>  $this->__max_media_size * 1024 * 1024,     /* 文件size的最大 1MB */
			);
			$upload = new FileUpload($config);
			$result = $upload->upload($fileInputName);
			$filepath = $dirmedia . $result['file_name'];
		
		}
		else if(in_array($ext,$allow_file_ext)){
			$dirfile = "/res/upload/mpe/".appId().'/'.trim($this->__file_save_path,'/') .'/'.date('Y')."/".date('m').'/';
			$config = array(
				"upload_dir" => APP_ROOT.$dirfile,
				//允许上传的文件类型(KB)
				'allow_ext' => str_replace(',','|',$this->__allow_file_ext),
				//文件的最大尺寸
				'max_size' =>  $this->__max_file_size * 1024,     /* 文件size的最大 1MB */
			);
			$upload = new FileUpload($config);
			$result = $upload->upload($fileInputName);
			$filepath = $dirfile . $result['file_name'];
		
		
		}
		if ( $result ) {
			AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, $filepath);
		} else {
		    //$max = $this->__max_file_size / 1024;
		    Log::info("上传出错,原因:".$upload->getUploadMessage());
			AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "文件过大或者文件格式错误");
			//AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "请上传小于{$max}MB的图片");
		}
	}

	public function uploadByOne(HttpRequest $request){


		if(count($_FILES) != 1){

			AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, L('PARAM_ERROR'));
		}
		$ext = '';
		foreach($_FILES  as $v)
		{
			$ext = $this->get_extension($v['name']);
		}
		$allow_file_ext = explode(',',$this->__allow_file_ext);
		$allow_image_ext = explode(',',$this->__allow_image_ext);
		$allow_media_ext = explode(',',$this->__allow_media_ext);
		if(in_array($ext,$allow_image_ext))
		{
			$dirimage = "/res/upload/mpe/".appId().'/'.trim($this->__image_save_path,'/') .'/'.date('Y')."/".date('m') .'/';
			$config = array(
				"upload_dir" => APP_ROOT.$dirimage,
				//允许上传的文件类型
				'allow_ext' => str_replace(',','|',$this->__allow_image_ext),
				//图片的最大宽度, 0没有限制
				'max_width' => 0,
				//图片的最大高度, 0没有限制
				'max_height' => 0,
				//文件的最大尺寸(KB)
				'max_size' =>  $this->__max_image_size * 1024,     /* 文件size的最大 1MB */
			);
			$upload = new FileUpload($config);
			$result = $upload->upload('src');
			$filepath = $dirimage . $result['file_name'];

		}
		else if(in_array($ext,$allow_media_ext))
		{
			$dirmedia = "/res/upload/mpe/".appId().'/'.trim($this->__media_save_path,'/') .'/'.date('Y')."/".date('m').'/';
			$config = array(
				"upload_dir" => APP_ROOT.$dirmedia,
				//允许上传的文件类型
				'allow_ext' => str_replace(',','|',$this->__allow_media_ext),
				//文件的最大尺寸(MB)
				'max_size' =>  $this->__max_media_size * 1024 * 1024,     /* 文件size的最大 1MB */
			);
			$upload = new FileUpload($config);
			$result = $upload->upload('src');
			$filepath = $dirmedia . $result['file_name'];

		}
		else if(in_array($ext,$allow_file_ext)){
			$dirfile = "/res/upload/mpe/".appId().'/'.trim($this->__file_save_path,'/') .'/'.date('Y')."/".date('m').'/';
			$config = array(
				"upload_dir" => APP_ROOT.$dirfile,
				//允许上传的文件类型(KB)
				'allow_ext' => str_replace(',','|',$this->__allow_file_ext),
				//文件的最大尺寸
				'max_size' =>  $this->__max_file_size * 1024,     /* 文件size的最大 1MB */
			);
			$upload = new FileUpload($config);
			$result = $upload->upload('src');
			$filepath = $dirfile . $result['file_name'];


		}


		if ( $result ) {

			return $filepath;
		} else {

			return $upload->getUploadMessage();
		}
	}

	private function get_extension($filename) {
		$pos = strrpos($filename, ".");
		return substr($filename,$pos + 1);
	}
	private function show_image($image, $img_url) {

		$info = pathinfo($img_url);
		switch ( strtolower($info["extension"]) ) {
			case "jpg":
			case "jpeg":
			header('content-type:image/jpg;');
			imagejpeg($image);
			break;

			case "gif":
			header('content-type:image/gif;');
			imagegif($image);
			break;

			case "png":
			header('content-type:image/png;');
			imagepng($image);
			break;

			default:
			header('content-type:image/wbmp;');
			image2wbmp($image);
		}

	}

	//编辑器上传方法 ， 仅允许上传图片
	public function kindeditor_upload(HttpRequest $request){

		//文件保存目录URL
		$save_url =  '/res/upload/mpe/'.appId().'/' . trim($this->__image_save_path,'/').'/'.date('Y').'/'.date('m') . '/';

		//文件保存目录路径
		$save_path =  APP_ROOT . $save_url;
		//定义允许上传的文件扩展名
		//只允许上传图片
		$ext_arr = array(
			'image' => explode(',',$this->__allow_image_ext),
		//	'media' => explode(',',$this->__allow_media_ext),
		//	'file' => explode(',',$this->__allow_file_ext),
		);
		//最大文件大小
		$max_size = $this->__max_image_size * 1024;

		FileUtils::makeFileDirs($save_path);

		$save_path = realpath($save_path) . '/';

		//PHP上传失败
		if (!empty($_FILES['imgFile']['error'])) {
			switch($_FILES['imgFile']['error']){
				case '1':
				$error = '超过php.ini允许的大小。';
				break;
				case '2':
				$error = '超过表单允许的大小。';
				break;
				case '3':
				$error = '图片只有部分被上传。';
				break;
				case '4':
				$error = '请选择图片。';
				break;
				case '6':
				$error = '找不到临时目录。';
				break;
				case '7':
				$error = '写文件到硬盘出错。';
				break;
				case '8':
				$error = 'File upload stopped by extension。';
				break;
				case '999':
				default:
				$error = '未知错误。';
			}
			$this->alert($error);
		}

		//有上传文件时
		if (empty($_FILES) === false) {
			//原文件名
			$file_name = $_FILES['imgFile']['name'];
			//服务器上临时文件名
			$tmp_name = $_FILES['imgFile']['tmp_name'];
			//文件大小
			$file_size = $_FILES['imgFile']['size'];
			//检查文件名
			if (!$file_name) {
				$this->alert("请选择文件。");
			}
			//检查目录
			if (@is_dir($save_path) === false) {
				$this->alert("上传目录不存在。");
			}
			//检查目录写权限
			if (@is_writable($save_path) === false) {
				$this->alert("上传目录没有写权限。");
			}
			//检查是否已上传
			if (@is_uploaded_file($tmp_name) === false) {
				$this->alert("上传失败。");
			}
			//检查文件大小
			if ($file_size > $max_size) {
				$this->alert("上传文件大小超过限制。");
			}
			//检查目录名
			$dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
			if (empty($ext_arr[$dir_name])) {
				$this->alert("目录名不正确。");
			}
			//获得文件扩展名
			$temp_arr = explode(".", $file_name);
			$file_ext = array_pop($temp_arr);
			$file_ext = trim($file_ext);
			$file_ext = strtolower($file_ext);
			//检查扩展名
			if (in_array($file_ext, $ext_arr[$dir_name]) === false) {
				$this->alert("上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。");
			}
			//创建文件夹
			if ($dir_name !== '') {
				$save_path .= $dir_name . "/";
				$save_url .= $dir_name . "/";
				if (!file_exists($save_path)) {
					mkdir($save_path);
				}
			}
			$ymd = date("Ymd");
			$save_path .= $ymd . "/";
			$save_url .= $ymd . "/";
			if (!file_exists($save_path)) {
				mkdir($save_path);
			}
			//新文件名
			$new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
			//移动文件
			$file_path = $save_path . $new_file_name;
			if (move_uploaded_file($tmp_name, $file_path) === false) {
				$this->alert("上传文件失败。");
			}
			@chmod($file_path, 0644);
			$file_url = $save_url . $new_file_name;

			header('Content-type: text/html; charset=UTF-8');
			echo json_encode(array('error' => 0, 'url' => $file_url));
			exit;
		}

	}

	// 删除上传资源 ，放入垃圾回收队列 ，等待删除
	// 
	public function delete(HttpRequest $request)
	{
		// 要删除的资源
		$file = $request->getParameter('file');
		// 资源引用记录所在的表
		$table = $request->getParameter('table');
		// 资源引用记录存储的字段
		$field = $request->getParameter('field');
		// 资源引用记录id 
		$id = $request->getParameter('id');
		if(!$file || !$table || !$field)
		{
			AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,L('PARAM_ERROR'));
		}

		$gcService = Beans::get('admin.gcResource.service');
		$gcService->gc($file,$table,$field,$id);
		AjaxResult::ajaxSuccessResult();


	}
	private function alert($msg) {
		header('Content-type: text/html; charset=UTF-8');
		echo json_encode(array('error' => 1, 'message' => $msg));
		exit;
	}
}
